package com.yld.car.market;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Random;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.text.ClipboardManager;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.Toast;

import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.SendMessageToWX;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.mm.sdk.openapi.WXMediaMessage;
import com.tencent.mm.sdk.openapi.WXTextObject;
import com.tencent.mm.sdk.openapi.WXWebpageObject;
import com.yld.car.application.MyApplication;
import com.yld.car.common.ConstantUtils;
import com.yld.car.common.ImageUtils;
import com.yld.car.common.NetworkProgressUtils;
import com.yld.car.common.Util;

public class CarInfoShareWayActivity extends BaseActivity {

	private IWXAPI api;

	private MyApplication mApp;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.car_info_share_way);
		mApp = super.mApp;
		api = WXAPIFactory.createWXAPI(this, ConstantUtils.APP_ID, false);
		api.registerApp(ConstantUtils.APP_ID);// 注册分享的应用

		Intent intent = this.getIntent();
		mSmsText = intent.getStringExtra("smsText");
		imageUrl = intent.getStringExtra("imageUrl");
		// System.out.println("url==="+imageUrl);
	}

	private String mSmsText;
	private String imageUrl;

	private String buildTransaction(final String type) {
		return (type == null) ? String.valueOf(System.currentTimeMillis())
				: type + System.currentTimeMillis();
	}

	class DownloadImageTask extends AsyncTask<String, String, String> {

		@Override
		protected String doInBackground(String... params) {
			try {
				// System.out.println("doInBack====>");
				FileOutputStream fis = new FileOutputStream(new File(
						Environment.getExternalStorageDirectory()
								.getAbsolutePath())
						+ "/test.jpg");

				System.out.println(Environment.getExternalStorageDirectory()
						.getAbsolutePath());
				InputStream inputStream = NetworkProgressUtils.getInstance()
						.getImageStream(mApp.getAllImageUrls().get(0));

				byte[] cache = new byte[1024];
				int index = 0;
				while ((index = inputStream.read(cache)) != -1) {

					fis.write(cache, 0, index);
				}

				fis.flush();
				fis.close();
				inputStream.close();
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			return "";
		}

	}

	private Button mButton;

	public void onAction(View v) {
		int id = v.getId();

		switch (id) {
		case R.id.shareButton1:
			//shareToFriendsOrWeChat(true);
			shareToWeChat(true);
			break;

		case R.id.shareButton2:
			//shareToFriendsOrWeChat(false);
			shareToWeChat(false);
			break;
		case R.id.shareButton3:
			shareToMessage();
			break;

		case R.id.shareButton4:

			shareToUrl();
			break;

		case R.id.shareButton5:
			copyUrlAddress();
			break;

		case R.id.shareCancel:
			finish();
			break;
		}

	}

	/**
	 * 分享到微信或者朋友圈
	 * 
	 * @param isWechat
	 */
	private void shareToFriendsOrWeChat(boolean isWechat) {

		if (!this.api.isWXAppInstalled()) {
			Toast.makeText(this, "该功能需要安装微信", Toast.LENGTH_SHORT).show();
			return;
		}
		if (!this.api.isWXAppSupportAPI()) {
			Toast.makeText(this, "您的微信版本不支持该功能，请升级微信。", Toast.LENGTH_SHORT)
					.show();
			return;
		}
		WXWebpageObject webpage = new WXWebpageObject();
		webpage.webpageUrl = mApp.getAllImageUrls().get(
				r.nextInt(mApp.getAllImageUrls().size()));
		WXMediaMessage msg = new WXMediaMessage(webpage);
		msg.title = "爱车行，行天下";
		if (mSmsText == null) {
			msg.description = "爱车，就请来爱车行吧！";
		} else {
			msg.description = mSmsText;
		}

		ArrayList<Bitmap> allBitmaps = mApp.getAllBitmaps();

		Bitmap thumb = null;
		if (allBitmaps.size() == 0) {
			thumb = BitmapFactory.decodeResource(getResources(),
					R.drawable.icon_home);
		} else {
			thumb = allBitmaps.get(1);
		}

		 msg.thumbData=ImageUtils.bitmapToByte(thumb);
		 System.out.println(thumb);
		thumb = Bitmap.createScaledBitmap(thumb, 100, 100, true);
		msg.thumbData = Util.bmpToByteArray1(thumb, true);
		SendMessageToWX.Req req = new SendMessageToWX.Req();
		req.transaction = buildTransaction("webpage");
		req.message = msg;
		req.scene = isWechat ? SendMessageToWX.Req.WXSceneSession
				: SendMessageToWX.Req.WXSceneTimeline;
		api.sendReq(req);
	}

	/**
	 * 分享短信
	 */
	private void shareToMessage() {

		Intent localIntent = new Intent("android.intent.action.SENDTO",
				Uri.parse("smsto:15823912195"));
		localIntent.putExtra("sms_body", mSmsText);
		startActivity(localIntent);
		finish();
	}

	private Random r = new Random();

	/**
	 * 打开网址
	 */

	private void shareToUrl() {

		Intent localIntent = new Intent("android.intent.action.VIEW",
				Uri.parse(mApp.getAllImageUrls().get(
						r.nextInt(mApp.getAllImageUrls().size()))));
		this.startActivity(localIntent);
		finish();
	}

	/**
	 * 复制链接
	 * 
	 */

	private void copyUrlAddress() {

		ClipboardManager mClipboardManager = (ClipboardManager) this
				.getSystemService(Context.CLIPBOARD_SERVICE);// 复制链接

		mClipboardManager.setText(mApp.getAllImageUrls().get(0));

		this.showDialogFinish("已复制到剪切板", true);
	}
	
	private void shareToWeChat(boolean flag){
		
		
		if (!this.api.isWXAppInstalled()) {
			Toast.makeText(this, "该功能需要安装微信", Toast.LENGTH_SHORT).show();
			return;
		}
		if (!this.api.isWXAppSupportAPI()) {
			Toast.makeText(this, "您的微信版本不支持该功能，请升级微信。", Toast.LENGTH_SHORT)
					.show();
			return;
		}
		WXTextObject textObj = new WXTextObject();

		//System.out.println("text===>" + text);
		String text=mSmsText;
		if(text==null){
			text="爱车行分享";
		}
		textObj.text = text;

		
		WXMediaMessage msg = new WXMediaMessage();
		msg.mediaObject = textObj;
		
		// msg.title = "Will be ignored";
		
		
		msg.description = text;

		
		SendMessageToWX.Req req = new SendMessageToWX.Req();
		req.transaction = buildTransaction("text");
		req.message = msg;
		req.scene =  flag?SendMessageToWX.Req.WXSceneSession:SendMessageToWX.Req.WXSceneTimeline;
				
		api.sendReq(req);
		
	}
}
